package com.dameng.jianyouquan.jobhunter.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.dameng.jianyouquan.R;
import com.dameng.jianyouquan.utils.DensityUtil;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.autosize.AutoSize;

public class JobDetailsActivity extends AppCompatActivity {


    @BindView(R.id.tv_job_name)
    TextView tvJobName;
    @BindView(R.id.mapView)
    MapView mMapView;

    private static final String PN_GAODE_MAP = "com.autonavi.minimap";// 高德地图包名
    private static final String PN_BAIDU_MAP = "com.baidu.BaiduMap"; // 百度地图包名
    private static final String PN_TENCENT_MAP = "com.tencent.map"; // 腾讯地图包名

    static double x_PI = 3.14159265358979324 * 3000.0 / 180.0;
    static double PI = 3.1415926535897932384626;
    static double a = 6378245.0;
    static double ee = 0.00669342162296594323;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job_detail);
        ButterKnife.bind(this);

        mMapView.onCreate(savedInstanceState);


        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(16);
        AMap aMap = mMapView.getMap();
        aMap.moveCamera(mCameraUpdate);
        LatLng latLng = new LatLng(34.761318, 113.770139);
        aMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("郑州").snippet("绿地之窗云峰座A座"));
        marker.showInfoWindow();


        findViewById(R.id.v_to_other_map).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog bottomDialog = new Dialog(JobDetailsActivity.this, R.style.BottomDialog);
                View contentView = LayoutInflater.from(JobDetailsActivity.this).inflate(R.layout.dialog_to_other_map, null);
                bottomDialog.setContentView(contentView);
                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
                params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(getApplicationContext(), 16f);
                params.bottomMargin = DensityUtil.dp2px(getApplicationContext(), 8f);
                contentView.setLayoutParams(params);
                bottomDialog.setCanceledOnTouchOutside(true);
                bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
                bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
                AutoSize.autoConvertDensity(JobDetailsActivity.this, 540, false);
                bottomDialog.show();

                boolean installgaode = isInstallPackage(PN_GAODE_MAP);
                boolean installbaidu = isInstallPackage(PN_BAIDU_MAP);
                boolean installtencent = isInstallPackage(PN_TENCENT_MAP);
                View vGaode = contentView.findViewById(R.id.ll_gaodemap);
                View vBaidu = contentView.findViewById(R.id.ll_baidumap);
                View vtencent = contentView.findViewById(R.id.ll_tencentmap);
                if (!installbaidu&&!installgaode&&!installtencent){
                    Toast.makeText(getApplicationContext(),"未发现地图软件",Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!installgaode){
                    vGaode.setVisibility(View.GONE);
                }

                if (!installbaidu){
                    vBaidu.setVisibility(View.GONE);
                }

                if (!installtencent){
                    vtencent.setVisibility(View.GONE);
                }

                vGaode.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        openGaoDeNavi(JobDetailsActivity.this, 34.761318, 113.770139, "绿地之窗");
                    }
                });

                vBaidu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

//                        double[] doubles = wgs84tobd09(113.770139, 34.761318);
                        double[] doubles = bd_encrypt(113.770139, 34.761318);
                        openBaiDuNavi(JobDetailsActivity.this, doubles[0], doubles[1], "绿地之窗");
//                        openBaiDuNavi(JobDetailsActivity.this, 34.761318, 113.770139, "绿地之窗");
                    }
                });

                vtencent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        openTencentMap(JobDetailsActivity.this, 34.761318, 113.770139, "绿地之窗");

                    }
                });

                contentView.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
            }
        });
    }


    private double[] bd_encrypt(double gg_lng, double gg_lat) {
        double X_PI = Math.PI * 3000.0 / 180.0;
        double x = gg_lng, y = gg_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
        double bd_lng = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;

        double[] arr = new double[2];

        arr[0] = bd_lat;
        arr[1] = bd_lng;
        return arr;

    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    private static boolean isInstallPackage(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }


    /**
     * 打开腾讯地图
     * params
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public void openTencentMap(Context context, double dlat, double dlon, String dname) {
//        public void openTencentMap(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
        String uriString = null;
        StringBuilder builder = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=zhongshuo");
//        if (slat != 0) {
//            builder.append("&from=").append(sname)
//                    .append("&fromcoord=").append(slat)
//                    .append(",")
//                    .append(slon);
//        }
        builder.append("&to=").append(dname)
                .append("&tocoord=").append(dlat)
                .append(",")
                .append(dlon);
        uriString = builder.toString();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage(PN_TENCENT_MAP);
        intent.setData(Uri.parse(uriString));
        context.startActivity(intent);
    }


    /**
     * 打开百度地图导航功能(默认坐标点是高德地图，需要转换)
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public void openBaiDuNavi(Context context, double dlat, double dlon, String dname) {
//        public void openBaiDuNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
        String uriString = null;
        //终点坐标转换  需要实现的在此处进行坐标转换

        double destination[] = gaoDeToBaidu(dlat, dlon);
        dlat = destination[0];
        dlon = destination[1];

        StringBuilder builder = new StringBuilder("baidumap://map/direction?mode=driving&");
//        if (slat != 0) {
//            //起点坐标转换
//
//            double[] origin = gaoDeToBaidu(slat, slon);
//            slat = origin[0];
//            slon = origin[1];
//
//            builder.append("origin=latlng:")
//                    .append(slat)
//                    .append(",")
//                    .append(slon)
//                    .append("|name:")
//                    .append(sname);
//        }
        builder.append("&destination=latlng:")
                .append(dlat)
                .append(",")
                .append(dlon)
                .append("|name:")
                .append(dname);
        uriString = builder.toString();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage(PN_BAIDU_MAP);
        intent.setData(Uri.parse(uriString));
        context.startActivity(intent);
    }

    private double[] gaoDeToBaidu(double dlat, double dlon) {
        return new double[]{dlat, dlon};
    }


    /**
     * 打开高德地图导航功能
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public void openGaoDeNavi(Context context, double dlat, double dlon, String dname) {
//        public void openGaoDeNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
        String uriString = null;
        StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=maxuslife");
//        if (slat != 0) {
//            builder.append("&sname=").append(sname)
//                    .append("&slat=").append(slat)
//                    .append("&slon=").append(slon);
//        }
        builder.append("&dlat=").append(dlat)
                .append("&dlon=").append(dlon)
                .append("&dname=").append(dname)
                .append("&dev=0")
                .append("&t=0");
        uriString = builder.toString();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage(PN_GAODE_MAP);
        intent.setData(Uri.parse(uriString));
        context.startActivity(intent);
    }


    private static double[] wgs84tobd09(double lng, double lat) {


        //第一次转换
        double dlat = transformlat(lng - 105.0, lat - 35.0);
        double dlng = transformlng(lng - 105.0, lat - 35.0);
        double radlat = lat / 180.0 * PI;
        double magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        double sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
        double mglat = lat + dlat;
        double mglng = lng + dlng;

        //第二次转换
        double z = Math.sqrt(mglng * mglng + mglat * mglat) + 0.00002 * Math.sin(mglat * x_PI);
        double theta = Math.atan2(mglat, mglng) + 0.000003 * Math.cos(mglng * x_PI);
        double bd_lng = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        double[] arr = new double[2];

        arr[0] = bd_lat;
        arr[1] = bd_lng;
        return arr;
    }


    private static double transformlat(double lng, double lat) {
        double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    private static double transformlng(double lng, double lat) {
        double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }


}
